package handler

import (
	"gift/api/request"
	"gift/internal/dao"
	"gift/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddPlay(c *gin.Context) {
	var req request.AddPlay
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	play := model.Play{
		Userid:  uint(req.Userid),
		Content: req.Content,
	}
	if !dao.Create(&play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": play,
	})
	return
}

func FindPlay(c *gin.Context) {
	var req request.FindPlay
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	play := model.Play{
		Content: req.Content,
	}
	if !dao.FindAll(&play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": play,
	})
	return
}

func UpdatePlay(c *gin.Context) {
	var req request.UpdatePlay
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var play model.Play
	if !dao.GetOneById(uint(req.Id), &play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	play = model.Play{
		Id:      uint(req.Id),
		Content: req.Content,
	}
	if !dao.Update(&play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "编辑失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": play,
	})
	return
}

func DeletePlay(c *gin.Context) {
	var req request.DeletePlay
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var play model.Play
	if !dao.GetOneById(uint(req.Id), &play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if !dao.Delete(&play) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": play,
	})
	return
}
